package com.example.myapplication1.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class OrderManager {
    private static final String TAG = "OrderManager";
    private DatabaseHelper dbHelper;
    private Context context;

    public OrderManager(Context context) {
        this.context = context;
        dbHelper = new DatabaseHelper(context);
    }

    public static class OrderItem {
        public String productName;
        public int quantity;
        public double price;
        public String location;  // 添加位置信息

        public OrderItem(String productName, int quantity, double price, String location) {
            this.productName = productName;
            this.quantity = quantity;
            this.price = price;
            this.location = location;
        }
    }

    public long createOrder(long userId, double totalAmount, OrderItem[] items) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long orderId = -1;

        try {
            db.beginTransaction();

            // 创建订单
            ContentValues orderValues = new ContentValues();
            orderValues.put(DatabaseHelper.COLUMN_USER_ID, userId);
            orderValues.put(DatabaseHelper.COLUMN_TOTAL_AMOUNT, totalAmount);
            orderValues.put(DatabaseHelper.COLUMN_ORDER_STATUS, "completed");
            // 添加第一个订单项的位置作为订单位置
            if (items.length > 0) {
                orderValues.put("location", items[0].location);
            }

            orderId = db.insert(DatabaseHelper.TABLE_ORDERS, null, orderValues);

            // 添加订单详情
            for (OrderItem item : items) {
                ContentValues itemValues = new ContentValues();
                itemValues.put(DatabaseHelper.COLUMN_ORDER_ID, orderId);
                itemValues.put(DatabaseHelper.COLUMN_PRODUCT_NAME, item.productName);
                itemValues.put(DatabaseHelper.COLUMN_QUANTITY, item.quantity);
                itemValues.put(DatabaseHelper.COLUMN_PRICE, item.price);
                itemValues.put("location", item.location);  // 保存位置信息

                db.insert(DatabaseHelper.TABLE_ORDER_ITEMS, null, itemValues);

                // 更新用户商品数量
                updateUserProducts(db, userId, item.productName, item.quantity);
            }

            db.setTransactionSuccessful();
            Log.d(TAG, "Order created successfully with ID: " + orderId);
            return orderId;

        } catch (Exception e) {
            Log.e(TAG, "Error creating order", e);
            return -1;
        } finally {
            if (db.inTransaction()) {
                db.endTransaction();
            }
        }
    }

    private void updateUserProducts(SQLiteDatabase db, long userId, String productName, int quantity) {
        // 查询用户是否已有该商品
        Cursor cursor = db.query(DatabaseHelper.TABLE_USER_PRODUCTS,
                new String[]{DatabaseHelper.COLUMN_REMAINING_QUANTITY},
                DatabaseHelper.COLUMN_USER_ID + "=? AND " + DatabaseHelper.COLUMN_PRODUCT_NAME + "=?",
                new String[]{String.valueOf(userId), productName},
                null, null, null);

        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_PRODUCT_NAME, productName);
        values.put(DatabaseHelper.COLUMN_USER_ID, userId);

        if (cursor != null && cursor.moveToFirst()) {
            // 更新现有数量
            int currentQuantity = cursor.getInt(0);
            values.put(DatabaseHelper.COLUMN_REMAINING_QUANTITY, currentQuantity + quantity);
            
            db.update(DatabaseHelper.TABLE_USER_PRODUCTS, values,
                    DatabaseHelper.COLUMN_USER_ID + "=? AND " + DatabaseHelper.COLUMN_PRODUCT_NAME + "=?",
                    new String[]{String.valueOf(userId), productName});
        } else {
            // 创建新记录
            values.put(DatabaseHelper.COLUMN_REMAINING_QUANTITY, quantity);
            db.insert(DatabaseHelper.TABLE_USER_PRODUCTS, null, values);
        }

        if (cursor != null) {
            cursor.close();
        }
    }
} 